package com.ys.service.hr.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.EditDto;
import com.ys.entity.hr.ThrVatApplyDetailCbb;
import com.ys.mapper.hr.HrMapper;
import com.ys.mapper.hr.ThrVatApplyDetailCbbMapper;
import com.ys.service.hr.ThrVatApplyDetailService;
import com.ys.vo.R;

@Service("thrVatApplyDetailService")
public class ThrVatApplyDetailServiceImpl implements ThrVatApplyDetailService {

	@Autowired
	private HrMapper hrMapper;
	@Autowired
	private ThrVatApplyDetailCbbMapper thrVatApplyDetailCbbMapper;
	
	@Override
	@Transactional
	public R edit(Long id, String detailArr, Long menuId) throws Exception {
		
		/*
		 *  验证详情数据物料
		 *  1、VAT号不能为空
		 *  2、税额不能为空
		 *  3、申报周期不能为空
		 */
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		String ids = "";
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long cbbId = detailJO.getLong("cbbId");
			if (cbbId == null) {
				return R.error("C88文件ID不能为空");
			}
		}
		ids = ids.length() > 0 ? ids.substring(0, ids.length() - 1) : "";
		
		// 删除旧的详情数据
		hrMapper.deleteBatchThrVatApplyDetailCbbByDetailId(id);
		
		// 添加或更新申请明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long cbbId = detailJO.getLong("cbbId");

			ThrVatApplyDetailCbb thrVatApplyDetailCbb = ThrVatApplyDetailCbb.thrVatApplyDetailCbb(id, cbbId, 1);
			thrVatApplyDetailCbbMapper.insert(thrVatApplyDetailCbb);
		}
		
		return R.ok(EditDto.reloadPage("/web/hr/thrVatApply/toEdit?id=" + id));
	}
}
